//
//  HKScrollViewDelegateProxy.m
//  KSBridgeDesign
//
//  Created by huzhaoke on 2021/4/17.
//

#import "HKScrollViewDelegateProxy.h"

static BOOL isHookSel(SEL sel) {
    return (
            // UIScrollViewDelegate
            sel == @selector(scrollViewDidScroll:) ||
            sel == @selector(scrollViewDidEndScrollingAnimation:) ||
            sel == @selector(scrollViewDidEndDragging:willDecelerate:) ||
            sel == @selector(scrollViewDidEndDecelerating:)
            );
}

@implementation HKScrollViewDelegateProxy

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    NSObject *delegateForResonse;
    if ([self.otherDelegate respondsToSelector:sel]) {
        delegateForResonse = self.otherDelegate;
    }
    if ([self.delegate respondsToSelector:sel]) {
        delegateForResonse = self.delegate;
    }
    return delegateForResonse ? [delegateForResonse methodSignatureForSelector:sel] : nil;
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    if (isHookSel(invocation.selector)) {
        [self invokeInvocation:invocation delegate:self.otherDelegate];
    }
    [self invokeInvocation:invocation delegate:self.delegate];
}

- (BOOL)respondsToSelector:(SEL)aSelector {
    return [self.delegate respondsToSelector:aSelector] || [self.otherDelegate respondsToSelector:aSelector];
}

- (void)invokeInvocation:(NSInvocation *)invaocation delegate:(id)delegate {
    if ([delegate respondsToSelector:invaocation.selector]) {
        [invaocation invokeWithTarget:delegate];
    }
}

@end
